const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.post('/get-news-content', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { id } = req.body
  if (!Bee.StringUtils.isNumber(id)) return handleError(10003, '参数错误')

  // 查询资讯
  const [getNewsContentError, getNewsContentSuccess] = await to(
    db.query('SELECT * FROM news WHERE id = ?', [id])
  )
  if (getNewsContentError || !getNewsContentSuccess)
    return handleError(-1, getNewsContentError)
  // 如果没有这条资讯就响应 错误
  if (getNewsContentSuccess.length !== 1) return handleError(-1, '系统错误')

  // 查询用户是否对该资讯点击过
  const [findNewsHitsError, findNewsHits] = await to(
    db.query(
      'SELECT count(*) FROM news_hits WHERE news_id = ? AND user_id = ?',
      [id, validateTokenSuccess.id]
    )
  )
  if (findNewsHitsError || !findNewsHits)
    return handleError(-1, findNewsHitsError)
  if (findNewsHits[0]['count(*)'] === 0) {
    // 表中没有记录 说明 没有点击过
    // 插入记录
    const [insertNewsHitsError, insertNewsHits] = await to(
      db.query('INSERT INTO news_hits (news_id, user_id) VALUES (?, ?)', [
        id,
        validateTokenSuccess.id,
      ])
    )
    if (insertNewsHitsError || !insertNewsHits)
      return handleError(-1, insertNewsHitsError)

    // 查询 news_hits 表总数据条数
    const [getTotalError, NewsHitsTotal] = await to(
      db.query('SELECT count(*) FROM news_hits')
    )
    if (getTotalError || !NewsHitsTotal) return handleError(-1, getTotalError)
    const newsHitsTotal = NewsHitsTotal[0]['count(*)']
    console.log(newsHitsTotal)

    // 更新 news 表中 hits 字段
    const [updateNewsError, updateNewsSuccess] = await to(
      db.query('UPDATE news SET hits = ? WHERE id = ?', [newsHitsTotal, id])
    )
    if (updateNewsError || !updateNewsSuccess)
      return handleError(-1, updateNewsError)
  }

  return resp.json({
    code: 0,
    msg: status_code[0],
    data: getNewsContentSuccess[0] ? getNewsContentSuccess[0] : {},
  })
})

module.exports = router
